using System;
using System.Collections.Generic;
using UnityEngine;
using Debug = UnityEngine.Debug;
using Random = UnityEngine.Random;

[CreateAssetMenu(fileName = "MapConfig", menuName = "山中战纪/地图配置")]
public class MapConfig : ScriptableObject
{
    [Header("地图设置")]
    public int totalActs = 3;
    public int nodesPerAct = 12;
    public int creditRequirementForBoss = 10;

    [Header("节点配置")]
    public NodeDistribution nodeDistribution;
    public List<string> commonEnemies;
    public List<string> eliteEnemies;
    public List<string> bossEnemies;

    [Header("事件池")]
    public List<string> commonEvents;
    public List<string> rareEvents;

    [System.Serializable]
    public class NodeDistribution
    {
        [Range(0, 100)] public int learningPercent = 40;
        [Range(0, 100)] public int challengePercent = 20;
        [Range(0, 100)] public int marketPercent = 15;
        [Range(0, 100)] public int dormitoryPercent = 10;
        [Range(0, 100)] public int eventPercent = 15;
    }

    /// <summary>
    /// 生成新地图
    /// </summary>
    public MapData GenerateMap(int actNumber)
    {
        MapData mapData = new MapData
        {
            actNumber = actNumber,
            nodes = new Dictionary<string, MapNode>()
        };

        // 生成节点布局（树状结构）
        List<MapNode> allNodes = GenerateNodeLayout(actNumber);

        // 设置起始节点和Boss节点
        mapData.startNodeId = allNodes[0].nodeId;
        mapData.bossNodeId = allNodes[allNodes.Count - 1].nodeId;

        // 添加到字典
        foreach (MapNode node in allNodes)
        {
            mapData.nodes.Add(node.nodeId, node);
        }

        return mapData;
    }

    /// <summary>
    /// 生成节点布局
    /// </summary>
    private List<MapNode> GenerateNodeLayout(int actNumber)
    {
        List<MapNode> nodes = new List<MapNode>();
        int nodeCount = nodesPerAct;

        // 创建节点
        for (int i = 0; i < nodeCount; i++)
        {
            NodeType nodeType = GetRandomNodeType();
            string nodeId = $"act{actNumber}_node{i}";
            string nodeName = GetNodeName(nodeType, i);
            Vector2 position = CalculateNodePosition(i, nodeCount);

            MapNode node = new MapNode(nodeId, nodeName, nodeType, position);

            // 设置节点特定内容
            SetupNodeContent(node, actNumber);

            nodes.Add(node);
        }

        // 建立连接关系（树状结构）
        BuildNodeConnections(nodes);

        return nodes;
    }

    /// <summary>
    /// 获取随机节点类型
    /// </summary>
    private NodeType GetRandomNodeType()
    {
        int rand = Random.Range(0, 100);
        int cumulative = 0;

        cumulative += nodeDistribution.learningPercent;
        if (rand < cumulative) return NodeType.Learning;

        cumulative += nodeDistribution.challengePercent;
        if (rand < cumulative) return NodeType.ChallengeTeacher;

        cumulative += nodeDistribution.marketPercent;
        if (rand < cumulative) return NodeType.Market;

        cumulative += nodeDistribution.dormitoryPercent;
        if (rand < cumulative) return NodeType.Dormitory;

        return NodeType.Event;
    }

    /// <summary>
    /// 设置节点内容
    /// </summary>
    private void SetupNodeContent(MapNode node, int actNumber)
    {
        switch (node.nodeType)
        {
            case NodeType.Learning:
                node.enemyIds.Add(GetRandomEnemy(commonEnemies));
                break;

            case NodeType.ChallengeTeacher:
                node.enemyIds.Add(GetRandomEnemy(eliteEnemies));
                break;

            case NodeType.Boss:
                node.enemyIds.Add(bossEnemies[actNumber - 1]);
                break;

            case NodeType.Event:
                node.eventIds.Add(GetRandomEvent());
                break;
        }
    }

    /// <summary>
    /// 建立节点连接
    /// </summary>
    private void BuildNodeConnections(List<MapNode> nodes)
    {
        // 简化的树状连接逻辑
        for (int i = 0; i < nodes.Count - 1; i++)
        {
            MapNode currentNode = nodes[i];

            // 每个节点连接1-3个后续节点
            int connections = Random.Range(1, 4);
            for (int j = 1; j <= connections && i + j < nodes.Count; j++)
            {
                currentNode.neighborIds.Add(nodes[i + j].nodeId);
            }
        }
    }

    private string GetRandomEnemy(List<string> enemyPool)
    {
        return enemyPool[Random.Range(0, enemyPool.Count)];
    }

    private string GetRandomEvent()
    {
        return commonEvents[Random.Range(0, commonEvents.Count)];
    }

    private string GetNodeName(NodeType type, int index)
    {
        return type switch
        {
            NodeType.Learning => $"练习课{index + 1}",
            NodeType.ChallengeTeacher => $"导师挑战{index + 1}",
            NodeType.Market => "校园集市",
            NodeType.Dormitory => "学生宿舍",
            NodeType.Event => "校园事件",
            NodeType.Boss => "期末考试",
            _ => $"节点{index + 1}"
        };
    }

    private Vector2 CalculateNodePosition(int index, int totalNodes)
    {
        float x = (float)index / (totalNodes - 1);
        float y = Random.Range(-0.2f, 0.2f);
        return new Vector2(x, y);
    }
}